<?php

/**
 * Description of entidad
 *
 * @author Federico del valle (quaidy@gmail.com)
 */
class entidad {
  protected $fields = array();
  protected $db_table = "";
  protected $inserted_id =  "";
  protected $pk = "";

  public function __construct() {
    $this->db_table= __CLASS__."s"; //tabla
  }
  
  public function cargarPorId($id) {
    $id_field = "id" . $this->db_table;
    $query = "SELECT * from ".$this->db_table." WHERE ".$id_field."=".$id;
    $rs = conexionManager::ejecutarQuery($query);
    $row = $rs->get_row();
    $this->loadByArray($row);
  }

  public function setClaves($clavesArray) {
    foreach ($clavesArray as $key => $valor) {
      $this->fields[$key] = $valor;
    }
  }

  public function loadByArray($array) {
    foreach ($array as $key => $value) {
      $this->fields[$key] = $value;
    }
  }

  
  public function grabar($tabla = "usuarios") {
    $query = queryManager::hacerInsert($this->fields, $tabla);
    $result = conexionManager::ejecutarQuery($query);
    $this->inserted_id = $result->inserted_id();
    return $result->exito();
  }

  public function set($clave,$valor) {
    $this->fields[$clave] = $valor;
  }

  public function get($clave) {
    if (isset($this->fields[$clave])) {
      return $this->fields[$clave];
    } else {
      return false;
    }
  }

  public function getDBTable() {
     return $this->db_table;
  }

  /**
   * Comprueba si un usuario existe y si existe lo carga
   * @param int $id
   * @return bool
   */
  public function existAndLoad($id,$key= '' ) {
    if (empty($key)) {
      $key = $this->pk;
    }
    $query = "SELECT * from ".$this->db_table." WHERE ".$key."=".$id;
    $rs = conexionManager::ejecutarQuery($query);
    if (($row = $rs->get_row())!= false) {
      $this->loadByArray($row);
      return true;
    } else {
      return false;
    }
  }

  public function exists($keys) {
    $query = "SELECT * from ".$this->db_table." WHERE ";
    foreach ($keys as $key => $value) {
      $query .= $key." = ".$value." AND ";
    }
    $query = substr($query, 0,  strlen($query)-5);
    $result = conexionManager::ejecutarQuery($query);
    if ($result->has_rows()) {
      return true;
    } else {
      return false;
    }
  }

  public function getKeyName() {
    if (isset($this->pk)) {
      return $this->pk;
    } else {
      return false;
    }
  }

  public function getKeyValue() {
    if (isset($this->fields[$this->pk])) {
      return $this->fields[$this->pk];
    } else {
      return false;
    }
  }


  public function borrarPorId($id) {
    $id_field= "id" . $this->db_table;
    $query = queryManager::hacerDelete($this->db_table, $id_field."=".$id);
    pr($query);
    $result = conexionManager::ejecutarQuery($query);
  }
}
?>
